package servlets;

import entities.UserEntity;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author andrei costache
 *
 */
public class UserLoginController extends UserController {

	@Override
	public void doRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
            RequestDispatcher view = null;
            String submitted = request.getParameter("submit");
            String redirect = null;
            if (submitted != null){
                UserEntity user = null;
                String email = request.getParameter("email");
                String pass = request.getParameter("password");
                boolean ok = true;
                //check if email is empty
                if (email == null || email.trim().equals("")){
                    msg.addStatusMessage("Please enter an email address!");
                    ok = false;
                } else {
                    //check if the (email, password) combination exists, and return the user entity.
                    user = userDAO.loadByEmailPassword(email, pass);
                    if (user == null){
                        msg.addStatusMessage("There is no user with this email and/or password!");
                        ok = false;
                    }
                }
                if (ok){
                    //Put the user into the session.
                    HttpSession session = request.getSession();
                    session.setAttribute("user", user);
                    //Redirect the user to the content list.
                    redirect = "/content/list";
                    msg.addStatusMessage("Welcome "+user.getFirstname()+" "+user.getLastname());
                }
                view = request.getRequestDispatcher("/jsp/UserLogin.jsp");
            } else {
                view = request.getRequestDispatcher("/jsp/UserLogin.jsp");
            }
            request.setAttribute("messages", msg);
            if (redirect != null){
                response.sendRedirect(request.getContextPath()+redirect);
            } else {
                view.forward(request, response);
            }
	}

}
